package com.wan.util.serializer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;

/**
 * 采用alibaba的json序列化
 */
public class FastjsonSerializer {

    public static String serializeStr(Object obj) {
        String serialStr = null;
        if (obj instanceof String) {
            //如果把字符串也序列化，那么字符串两侧会多添加一次双引号，造成错误。
            serialStr = (String) obj;
        } else {
            serialStr = JSON.toJSONString(obj);
        }
        return serialStr;
    }

    public static Object deserializeStr(String str,Class<?> type) {
        return str == null || str.equals("")  ? null : JSON.parseObject(str,type);
    }

    public static byte[] serialize(Object obj) {
        return JSON.toJSONString(obj, SerializerFeature.WriteClassName).getBytes();
    }

    public static Object deserialize(byte[] bytes) {
        return JSON.parse(new String(bytes), Feature.SupportAutoType);
    }

}
